import React, {FC, useCallback, useEffect, useMemo, useRef, useState} from "react";
import "./css/MenuFunAuth.less";
import {Input, Tree} from "antd";
import {AxiosGet, AxiosSer} from "../../../services/HttpService";
import {treeMap} from "../../../utils";
import {getLocale} from "../../../../i18n/i18n";
import {useTranslation} from "react-i18next";
import {addOkModal, closeModal} from "../../../services/ModalService";
import useStateRef from "../../../customUse/useStateRef";
import useThrottle from "../../../customUse/useThrottle";

interface MenuFunAuthProps {
    modalKey: string,
    flowData: any[]
}

const MenuFunAuth: FC<MenuFunAuthProps> = (props) => {
    const {t} = useTranslation();

    const menuAuthRef = useRef([]);
    const menuSelectRef = useRef([]);
    const menuHalfSelectRef = useRef([]);

    const [menuAuth, setMenuAuth] = useState<any[]>(),
        [menuSelectKeys, setMenuSelectKeys] = useStateRef([], menuSelectRef),
        [menuHalfSelectKeys, setMenuHalfSelectKeys] = useStateRef([], menuHalfSelectRef),
        [menuExpandKeys, setMenuExpandKeys] = useState<string[]>([]);

    const initMenuAuth = useCallback(async () => {
        let {flowData = []}: { flowData: any[] } = props, selectKeys: string[] = [], expandKeys: string[] = [];
        if (flowData[0]) {
            const {data = []}: { data: any[] } = await AxiosGet("/sf-drs/platform/funcGrant", {
                presetRoleId: flowData[0].id,
                parentMenuId: 0
            });
            let newMenuAuth = treeMap(data, (child: any[], node: any, parent: any, i: number, level: number) => {
                if (level === 0) {
                    expandKeys.push(node.id);
                }
                let newChild: any = undefined;
                if (child && child.length) {
                    newChild = child;
                    newChild.push({
                        id: node.id + "-onlyShow",
                        title: t("onlyAuthParentMenu"),
                        onlyShow: true,
                        priGrant: node.priGrant === "Y"
                    });
                    if (node.priGrant === "Y") {
                        selectKeys.push(node.id + "-onlyShow");
                    }
                } else {
                    if (node.priGrant === "Y") {
                        selectKeys.push(node.id);
                    }
                }
                return {
                    ...node,
                    title: getLocale(node.zhCn, node.usEn, node.ptBr) + (node.description ? "-" + node.description : ""),
                    priGrant: node.priGrant === "Y",
                    children: newChild
                }
            });
            menuAuthRef.current = newMenuAuth;
            setMenuAuth(newMenuAuth);
            setMenuSelectKeys(selectKeys);
            setMenuExpandKeys(expandKeys);
        }

    }, [props.flowData]);

    const onOk: Function = useThrottle(async () => {
        if (!menuSelectRef.current || !menuHalfSelectRef.current) {
            return;
        }
        const {flowData = []}: { flowData: any[] } = props
        let params: any = {
            presetRoleId: flowData[0].id,
            ids: [...menuSelectRef.current, ...menuHalfSelectRef.current].filter((i: any) => (i.indexOf("-onlyShow") === -1))
        }
        let result: any = await AxiosSer("/sf-drs/platform/funcGrant/grantFuncMenus", "POST", params) || {};
        result.code == "1" && await closeModal(props.modalKey, async () => {
            return {data: params, ...result};
        })
    }, 2000, []);

    useEffect(() => {
        initMenuAuth()
    }, [props.flowData]);

    useEffect(() => {
        addOkModal(props.modalKey, onOk);
    }, []);

    const handleSearch = useCallback((value: any) => {
        let expandKeys: string[] = [];
        if (menuAuthRef.current) {
            let newRoleAuth: any[] = treeMap(menuAuthRef.current, (child: any[], node: any) => {
                if (child && child.length > 1) {
                    expandKeys.push(node.id);
                    return {
                        ...node,
                        children: child
                    }
                }
                if (node.title.indexOf(value) !== -1 || node.id.indexOf("-onlyShow") !== -1) {
                    return {
                        ...node
                    }
                }
            })
            setMenuAuth(newRoleAuth);
            setMenuExpandKeys(expandKeys);
        }
    }, []);

    const handleCheck = useCallback((checkedKeys: string[], e: any) => {
        setMenuSelectKeys(checkedKeys);
        setMenuHalfSelectKeys(e.halfCheckedKeys);
    }, []);

    const handleExpand = useCallback((expandedKeys: string[]) => {
        setMenuExpandKeys(expandedKeys);
    }, []);

    const renderMenuFunAuth = useMemo(() => {
        let {flowData = []}: { flowData: any[] } = props;
        if (!menuAuth) {
            return null;
        }
        return (
            <div className="sf_core_menu_fun_auth">
                <div className="sf_core_menu_fun_auth_title">
                    {/* {t("name")}：{flowData[0]?.name} */}
                </div>
                <Input.Search onSearch={handleSearch}/>
                <Tree
                    showLine
                    checkable
                    blockNode
                    treeData={menuAuth}
                    onCheck={handleCheck}
                    onExpand={handleExpand}
                    expandedKeys={menuExpandKeys}
                    checkedKeys={menuSelectRef.current}
                    fieldNames={{key: "id"}}
                    // height={450}
                />
            </div>
        )
    }, [menuAuth, menuSelectKeys, menuExpandKeys]);

    return (renderMenuFunAuth);
}

export default React.memo(MenuFunAuth);